<?php
// Create the Widget
// Add Widget Action
add_action('widgets_init', 'jtw_data_register_widgets');

// Register Widget
function jtw_data_register_widgets() {
	register_widget('jtw_data_widget');
}

// jtw_data_widget Class
class jtw_data_widget extends WP_Widget {
	
	// process the new widget
	function jtw_data_widget() {
		$widget_ops = array(
			'classname' => 'jtw_data_widget_class',
			'description' => 'Manipulates some of the user\'s data'
		);
		$this->WP_Widget( 'jtw_data_widget', 'My Data Widget', $widget_ops);
	}
	
	// Build the widget settings form
	function form($instance) {
		$defaults = array('title' => '', 'data' => '');
		$instance = wp_parse_args( (array) $instance, $defaults );
		$title = $instance['title'];
		$data = $instance['data'];
		$show_defaults = $instance['show_defaults'];
		?>
		<p>Please Define Default Values</p>
		<p>Title: <input class="widefat" name="<?php echo $this->get_field_name('title'); ?>"
			type="text" value="<?php echo esc_attr( $title ); ?>" /></p>
		<p>Data: <input class="widefat" name="<?php echo $this->get_field_name('data'); ?>"
			type="text" value="<?php echo esc_attr( $data ); ?>" /></p>
		<p>Show Default Values? <input name="<?php echo $this->get_field_name( 'show_defaults' ); ?>" 
			type="checkbox" <?php checked($show_defaults, 'on'); ?> /></p>
				
		<?php
	}
	
	function update($new_instance, $old_instance) {
		$instance = $old_instance;
		$instance['title'] = esc_attr($new_instance['title']);
		$instance['data'] = esc_attr($new_instance['data']);
		$instance['show_defaults'] = strip_tags($new_instance['show_defaults']);
		
		return $instance;
	}
	
	//Display the widget
	function widget($args, $instance) {
		// If currently viewing a Post
		if(is_single()) {
			extract($args);
			
			// Get the meta Data
			global $post;
			$jtw_title_meta = get_post_meta( $post->ID, '_jtw_title_meta', true);
			$jtw_data_meta = get_post_meta( $post->ID, '_jtw_data_meta', true);
			
			// Get the instance Data
			$title = $instance['title'];
			$data = $instance['data'];
			$show_defaults = $instance['show_defaults'];
			
			// If There is meta data defined display it
			if( !empty($jtw_title_meta) ) {
				$jtw_title_meta = apply_filters( 'widget_title', $jtw_title_meta );
				
				echo $before_widget;
				echo $before_title . $jtw_title_meta . $after_title;
				echo "Data: " . $jtw_data_meta;
				echo $after_widget;
			}
			elseif ($show_defaults == 'on') {
				$title = apply_filters( 'widget_title', $instance['title'] );
				
				echo $before_widget;
				echo $before_title . $title . $after_title;
				echo "Default Data: " . $instance['data'];
				echo $after_widget;
			}
		}
	
	}
	
} // End Class jtw_data_widget
?>